"""
应用控制器：承上启下，连接UI与核心业务
"""
import os
import threading
import asyncio
from typing import Callable, Optional, Dict, Any
from dotenv import load_dotenv
from loguru import logger

from core import (
    MovieAPI,
    XianyuClient,
    set_gui_log_callback,
    set_gui_show_antispam_callback,
)


class AppController:
    def __init__(self):
        load_dotenv()
        self.movie_api = MovieAPI()
        self.xianyu_client: Optional[XianyuClient] = None
        self._ws_thread: Optional[threading.Thread] = None

    # ========== 配置相关 ==========
    def read_env(self) -> Dict[str, str]:
        load_dotenv()
        return {
            'AppID': os.getenv('AppID', ''),
            'AppSecret': os.getenv('AppSecret', ''),
            'DEBUG': os.getenv('DEBUG', 'true').lower(),
            'COOKIE': os.getenv('COOKIE', ''),
            'PRICE_MARKUP_TYPE': os.getenv('PRICE_MARKUP_TYPE', '固定上浮'),
            'PRICE_MARKUP_VALUE': os.getenv('PRICE_MARKUP_VALUE', '0'),
        }

    def save_env(self, updates: Dict[str, str]) -> None:
        env_content = ''
        if os.path.exists('.env'):
            with open('.env', 'r', encoding='utf-8') as f:
                env_content = f.read()
        lines = env_content.split('\n') if env_content else []
        exist = set()
        result_lines = []
        for line in lines:
            k = line.split('=')[0] if '=' in line else ''
            if k in updates:
                result_lines.append(f"{k}={updates[k]}")
                exist.add(k)
            else:
                result_lines.append(line)
        for k, v in updates.items():
            if k not in exist:
                result_lines.append(f"{k}={v}")
        with open('.env', 'w', encoding='utf-8') as f:
            f.write('\n'.join(result_lines))
        load_dotenv()
        # 刷新movie api以使用新环境
        self.movie_api = MovieAPI()

    # ========== WebSocket 连接 ==========
    def connect_ws(
        self,
        cookie: str,
        on_connected: Callable[[], None],
        on_failed: Callable[[str], None],
        add_log: Callable[[str], None],
        show_antispam: Callable[[], None],
    ) -> None:
        def run():
            try:
                self.xianyu_client = XianyuClient(cookie)
                # 绑定回调到GUI
                set_gui_log_callback(add_log)
                set_gui_show_antispam_callback(show_antispam)
                on_connected()
                add_log('开始连接WebSocket服务...')
                asyncio.run(self.xianyu_client.main())
            except Exception as e:
                on_failed(str(e))

        self._ws_thread = threading.Thread(target=run, daemon=True)
        self._ws_thread.start()

    # ========== 订单相关 ==========
    def list_orders(self, page: int = 1, page_size: int = 30) -> Dict[str, Any]:
        return self.movie_api.movie_goofish_order_list(page, page_size)

    def confirm_shipment(self, order_no: str) -> Dict[str, Any]:
        return self.movie_api.movie_goofish_order_confirm(order_no)

    def order_info(self, buyer_id: str, seller_id: str, goods_id: str) -> Dict[str, Any]:
        return self.movie_api.movie_goofish_order_info(buyer_id, seller_id, goods_id)

